//
//  CommunityInteractionDetailViewController.m
//  ECBBusinessCamp
//
//  Created by rimi on 16/6/22.
//  Copyright © 2016年 邓毕华. All rights reserved.
//

#import "CommunityInteractionDetailViewController.h"

#import "CommentTableViewCell.h"
#import "InputView.h"

#define COMMENTTABLEVIEWCELLIDENTIFIEL @"commentTableViewCellIdentifier"
#define LABEL_TEXTCOLOR RGB_COLOR(80, 80, 80, 1)

@interface CommunityInteractionDetailViewController ()<UITableViewDataSource>

@property (nonatomic, strong) UITableView * commentTableView; // 评论表格视图
@property (nonatomic, strong) UIButton * backButton; // 返回按钮
@property (nonatomic, strong) InputView * inputView; // 输入视图
@property (nonatomic, strong) NSMutableDictionary * parameters; // 网络请求参数
@property (nonatomic, assign) NSInteger pageNum; // 记录列表页码
@property (nonatomic, strong) NSMutableArray * dataSource; // 网络请求下来的数据

@end

@implementation CommunityInteractionDetailViewController

#pragma mark 🌷🌷🌷life cycle🌷🌷🌷
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 添加视图
    [self.view addSubview:self.headImageView];
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.contentLabel];
    [self.view addSubview:self.nameLabel];
    [self.view addSubview:self.releaseDateLabel];
    [self.view addSubview:self.commentTableView];
    [self.view addSubview:self.backButton];
    [self.view addSubview:self.inputView];
    
    // 自动布局
    [_headImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(SCREEN_HEIGHT * 0.26 * 0.6);
        make.top.offset(SCREEN_HEIGHT * 0.12);
        make.left.offset(SCREEN_WIDTH * 0.023);
    }];
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(SCREEN_HEIGHT * 0.123);
        make.left.equalTo(_headImageView.mas_right).offset(SCREEN_WIDTH * 0.026);
    }];
    [_contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view).multipliedBy(0.954);
        make.left.equalTo(_headImageView);
        make.top.offset(SCREEN_HEIGHT * 0.327);
    }];
    [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_titleLabel);
        make.bottom.equalTo(_headImageView);
    }];
    [_releaseDateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_titleLabel);
        make.top.offset(SCREEN_HEIGHT * 0.16);
    }];
    [_commentTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view);
        make.height.equalTo(self.view).multipliedBy(0.42);
        make.top.offset(SCREEN_HEIGHT * 0.42);
        make.centerX.equalTo(self.view);
    }];
    [_backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(SCREEN_WIDTH * 0.065);
        make.left.offset(SCREEN_WIDTH * 0.06);
        make.bottom.offset(SCREEN_HEIGHT * -0.2);
    }];
    [_inputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view);
        make.height.equalTo(self.view).multipliedBy(0.06);
        make.centerX.equalTo(self.view);
        make.bottom.offset(SCREEN_HEIGHT * -0.09);
    }];
    
    // 添加刷新
    [self addRefresh];
    
    // 注册单元格
    [_commentTableView registerClass:[CommentTableViewCell self] forCellReuseIdentifier:COMMENTTABLEVIEWCELLIDENTIFIEL];
}
- (void)viewWillAppear:(BOOL)animated {
    // 第一次网络请求
    _pageNum = 0;
    [self loadData];
    
    _inputView.id = _id;
    
    // 添加键盘监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark 🌷🌷🌷UITableViewDataSource🌷🌷🌷
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:COMMENTTABLEVIEWCELLIDENTIFIEL forIndexPath:indexPath];
    
    // cell 赋值
    [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:BASEURLAPPEND(_dataSource[indexPath.row][@"userPic"])] placeholderImage:[UIImage imageNamed:@"default_head_s.png"]];
    cell.contentLabel.text = [NSString getEmojiStringForString:_dataSource[indexPath.row][@"msg"]];
    cell.playRecordButton.hidden = [_dataSource[indexPath.row][@"msg"] length] != 0;
    cell.nameLabel.text = _dataSource[indexPath.row][@"nickName"];
    cell.releaseDateLabel.text = _dataSource[indexPath.row][@"createTime"];
    cell.recordUrl = _dataSource[indexPath.row][@"url"];
    cell.clickBlock = ^(NSString * name) {
        _inputView.inputTextField.text = [NSString stringWithFormat:@"@%@:", name];
        if (![_inputView.inputTextField isFirstResponder]) {
            [_inputView respondsToInputBtn:_inputView.inputTypeButton];
        }
        _inputView.msgTo = _dataSource[indexPath.row][@"id"];
    };
    
    return cell;
}

#pragma mark 🌷🌷🌷event responds🌷🌷🌷
- (void)respondsToBackBtn {
    [UIView animateWithDuration:0.5 animations:^{
        self.view.center = CGPointMake(SCREEN_WIDTH * 1.5, SCREEN_HEIGHT * 0.5);
    } completion:^(BOOL finished) {
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
    }];
}
- (void)keyboardWillShow:(NSNotification *)notification {
    [self inputViewMoved:notification.userInfo isShow:YES];
}
- (void)keyboardWillHide:(NSNotification *)notification {
    [self inputViewMoved:notification.userInfo isShow:NO];
}

#pragma mark 🌷🌷🌷private methods🌷🌷🌷
- (void)addRefresh {
    _commentTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 下拉刷新
        _pageNum = 0;
        [self.dataSource removeAllObjects];
        [self loadData];
    }];
    _commentTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        // 下拉加载更多
        if (_dataSource.count < (_pageNum + 1) * 10) {
            [MBProgressHUD showError:@"没有更多数据！"];
            [_commentTableView.mj_footer endRefreshing];
            return ;
        }
        _pageNum += 1;
        [self loadData];
    }];
}
- (void)loadData {
    self.parameters[@"pageNum"] = @(_pageNum);
    [[NetTool sharedTool] requestMethod:POST loadingMsg:@"加载中..." url:BASEURLAPPEND(COMMUNITYINTERACTIONDETAIL_URL) parameters:_parameters finish:^(id responseObject, NSError *error) {
        if (!error) {
            [MBProgressHUD showSuccess:@"加载完成！"];
            [self.dataSource addObjectsFromArray:responseObject[@"data"]];
            [_commentTableView reloadData];
        }
        [_commentTableView.mj_header endRefreshing];
        [_commentTableView.mj_footer endRefreshing];
    }];
}
- (void)inputViewMoved:(NSDictionary *)userInfo isShow:(BOOL)isShow {
    // 键盘高度
    CGRect keyFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    double height = keyFrame.size.height;
    
    // 动画时长
    CGFloat durtion = [userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    [_inputView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(isShow ? -height : SCREEN_HEIGHT * -0.09);
    }];
    
    [UIView animateWithDuration:durtion animations:^{
        [self.view layoutIfNeeded];
    }];
}

#pragma mark 🌷🌷🌷getters and setters🌷🌷🌷
- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
- (UIImageView *)headImageView {
    if (!_headImageView) {
        _headImageView = [[UIImageView alloc] init];
    }
    return _headImageView;
}
- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font = [UIFont systemFontOfSize:28];
    }
    return _titleLabel;
}
- (UILabel *)contentLabel {
    if (!_contentLabel) {
        _contentLabel = [[UILabel alloc] init];
        _contentLabel.numberOfLines = 2;
        _contentLabel.font = [UIFont systemFontOfSize:25];
        _contentLabel.textColor = LABEL_TEXTCOLOR;
    }
    return _contentLabel;
}
- (UILabel *)nameLabel {
    if (!_nameLabel) {
        _nameLabel = [[UILabel alloc] init];
        _nameLabel.font = [UIFont systemFontOfSize:25];
        _nameLabel.textColor = LABEL_TEXTCOLOR;
    }
    return _nameLabel;
}
- (UILabel *)releaseDateLabel {
    if (!_releaseDateLabel) {
        _releaseDateLabel = [[UILabel alloc] init];
        _releaseDateLabel.textColor = LABEL_TEXTCOLOR;
        _releaseDateLabel.font = [UIFont systemFontOfSize:18];
    }
    return _releaseDateLabel;
}
- (UITableView *)commentTableView {
    if (!_commentTableView) {
        _commentTableView = [[UITableView alloc] init];
        // 设置数据源
        _commentTableView.dataSource = self;
        // 设置行高
        _commentTableView.rowHeight = SCREEN_HEIGHT * 0.16;
        // 去掉分隔线
        _commentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _commentTableView;
}
- (UIButton *)backButton {
    if (!_backButton) {
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backButton setImage:[UIImage imageNamed:@"btn_返回按钮.png"] forState:UIControlStateNormal];
        [_backButton addTarget:self action:@selector(respondsToBackBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backButton;
}
- (InputView *)inputView {
    if (!_inputView) {
        _inputView = [[InputView alloc] initWithClickRefreshBlock:^{
            _inputView.inputTextField.text = @"";
            [_inputView.inputTextField resignFirstResponder];
            [_commentTableView.mj_header beginRefreshing];
        }];
    }
    return _inputView;
}
- (NSMutableDictionary *)parameters {
    if (!_parameters) {
        _parameters = [NSMutableDictionary dictionaryWithObjects:@[_id, @(0), @(10)] forKeys:@[@"id", @"pageNum", @"pagesize"]];
    }
    return _parameters;
}

@end
